package cn.phantom.pooltest;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.RecursiveTask;

@Slf4j(topic = "c.TestForkJoin02")
public class TestForkJoin02 {
    public static void main(String[] args) {
        ForkJoinPool pool = new ForkJoinPool(4);
        System.out.println(pool.invoke(new AddTask(1, 5)));
    }
}

class AddTask extends RecursiveTask<Integer> {

    int begin;
    int end;

    public AddTask(int begin, int end) {
        this.begin = begin;
        this.end = end;
    }

    @Override
    protected Integer compute() {
        if (begin == end) {
            return begin;
        }
        if (end - begin == 1) {
            return end + begin;
        }
        int mid = (end + begin) / 2; // 3

        AddTask t1 = new AddTask(begin, mid); // 1, 3
        t1.fork();

        AddTask t2 = new AddTask(mid + 1, end); // 4, 5
        t2.fork();

        int res = t1.join() + t2.join();
        return res;
    }
}
